  const {getTokenAPI,getLoginApi} = require('../http/api')
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

async function getToken() {
  const token =  wx.getStorageSync('token')
  // console.log(token)
  if(!token){
    return false
  }
  const res = await getTokenAPI(token)
  // console.log(res);
  if(res.code!==0){
    wx.removeStorageSync('token')
    return false
  }
  const flag = await staus()
  if(!flag){
    wx.removeStorageSync('token')
    return false
  }


  // if(!token || !flag || res.code!==0){
  //   if(token){
  //     wx.removeStorageSync('token')
  //   }
  //   return false
  // }
  return true
}

// 判断小程序是否在后台有效期内
function staus() {
  return new Promise((resolve,reject)=>{
    wx.checkSession({
      success(){
        resolve(true)
      },
      fail(){
        resolve(false)
      }
    })
  })
}

// 如果三个条件不成立，需要重新调用登录接口
function login() {
  wx.login({
    async success(res){
        if(res.code){
          console.log(res.code)
          const data = await getLoginApi(res.code)
          const {openid, token, uid} = data.data 
          wx.setStorageSync('token', token)
          wx.setStorageSync('uid', uid)
        }
    }
  })
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

module.exports = {
  formatTime,
  getToken,
  login
}
